<?php
/**
 * Created by Alfred.
 * Date: 2021/7/21
 * Email: silentwolf_wp@163.com
 */

namespace app\demo\controller;


use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class MqProducer
{
    public static function pushMessage($data)
    {
        $param = config('rabbitmq.AMQP');
        $amqpDetail = config('rabbitmq.email_queue');
        $connection = new AMQPStreamConnection(
            $param['host'],
            $param['port'],
            $param['login'],
            $param['password'],
            $param['vhost']
        );
        $channel = $connection->channel();
        $json_data = json_decode($data,true);
        $exchange_name = $amqpDetail['exchange_name2'];
        if($json_data['index']%2==0){
            $queue_name = $amqpDetail['queue_name2'];
            $routekey = $amqpDetail['route_key2'];
//            $exchange_name = $amqpDetail['exchange_name2'];
        }else{
            $queue_name = $amqpDetail['queue_name'];
            $routekey = $amqpDetail['route_key'];
//            $exchange_name = $amqpDetail['exchange_name'];
        }
        /*
            name: $exchange  创建交换机
            type: direct   直连方式
            passive: false
            durable: true  持久// 交换器将在服务器重启后继续存在
            auto_delete: false //一旦通道关闭，交换器将不会被删除。
        */
        $channel->exchange_declare($exchange_name, $amqpDetail['exchange_type'], false, true, false);
        /*
             name: $queue  创建队列
             passive: false
             持久durable: true // //队列将在服务器重启后继续存在
             互斥exclusive: false // 队列可以通过其他渠道访问
             auto_delete: false 通道关闭后，队列不会被删除
         */
        $channel->queue_declare($queue_name, false, true, false, false);
        $channel->queue_bind($queue_name,$exchange_name);//队列绑定交换器
        /*
             $messageBody:消息体
             content_type:消息的类型 可以不指定
             delivery_mode:消息持久化最关键的参数
             AMQPMessage::DELIVERY_MODE_NON_PERSISTENT = 1;
             AMQPMessage::DELIVERY_MODE_PERSISTENT = 2;
         */
//        $messageBody = $data;
        $messageBody = $json_data['msg'];
        $message = new AMQPMessage($messageBody, array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT));
        $channel->basic_publish($message, $exchange_name,$routekey);
        $channel->close();
        $connection->close();
        echo "<pre>";
        echo  $json_data['msg']." 发送成功!"."</br>";
    }
}